/*
 * fonte: http://victorserta.com.br/blog/2008/12/11/programacao-concorrente-com-javautilconcurrent-parte-1/
 */

package br.com.aggjpsv.libraryserver.thread;

import br.com.aggjpsv.libraryserver.FactoryAbstract;
import br.com.aggjpsv.libraryserver.entities.Request;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 *
 * @author Sérgio C. Peres
 */
public class HTTPReplyBasic implements Runnable{
    
    private FactoryAbstract factory;
    private Socket socket;
    
    public HTTPReplyBasic(FactoryAbstract factory, Socket socket) {
        this.factory = factory;
        this.socket = socket;
    }
    
    @Override
    public void run() {
        file();
    }
    
    private void file() {
        InetAddress infoCliente;
        HTTPResponseBasic res;
        
        InputStream input = null;
        OutputStream output = null;
        
        try {
            infoCliente = socket.getInetAddress();
            //System.out.println("\nCliente: " + infoCliente.getHostName() + " conectou ao servidor!");
            
            input = socket.getInputStream();
            output = socket.getOutputStream();
            
            String requestString = factory.convertStreamToString(input);
            System.out.println("Conexão recebida. Conteúdo:\n" + requestString);
            Request request = factory.getRequest(requestString);
            
            res = factory.getRespose(output);
            if (res.setRequest(request.getHead().getMethod(),request.getHead().getUri()))
            {
                res.sendResponse(request);
            }
            input.close();
            output.close();
        } catch (java.io.IOException ex) {
            System.out.println("Erro de Conexão: " + ex.getMessage());
        } finally {
            try {
                socket.close();
            } catch (java.io.IOException ex) {
                System.out.println("Erro ao tetar enserar um socket da thread....\n Erro: " + ex.getMessage());
            }
        }
    }
}
